package com.resource.transactions.service.impl;

import com.resource.transactions.entities.RResource;
import com.resource.transactions.service.SolrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
@Slf4j
public class SolrServiceImpl implements SolrService {

    @Resource
    private SolrClient solrClient;

    @Override
    public UpdateResponse add(RResource rResource) throws IOException, SolrServerException {
        SolrInputDocument document = new SolrInputDocument();
        document.setField("id", rResource.getResourceid());
        document.setField("resource_id", rResource.getResourceid());
        document.setField("resource_name", rResource.getResourcename());
        document.setField("resource_path", rResource.getResourcepath());
        document.setField("resource_datetime", rResource.getResourcedatetime());
        document.setField("resource_typeid", rResource.getTypeid());
        document.setField("resource_userid", rResource.getUserid());
        solrClient.add(document);
        return solrClient.commit();
    }

    @Override
    public UpdateResponse delete(String productId) throws IOException, SolrServerException {
        solrClient.deleteById(productId);
        return solrClient.commit();
    }

    @Override
    public UpdateResponse update(RResource rResource) throws IOException, SolrServerException {
        SolrInputDocument document = new SolrInputDocument();
        document.addField("id", rResource.getResourceid());
        document.addField("resource_id", rResource.getResourceid());
        document.addField("resource_name", rResource.getResourcename());
        document.addField("resource_path", rResource.getResourcepath());
        document.addField("resource_datetime", rResource.getResourcedatetime());
        document.addField("resource_typeid", rResource.getTypeid());
        document.addField("resource_userid", rResource.getUserid());
        solrClient.addBean(document);
        return solrClient.commit();
    }

    @Override
    public SolrDocumentList query(String resourceName) throws IOException, SolrServerException {
        SolrQuery solrQuery = new SolrQuery();

        solrQuery.setQuery("resource_name:" + resourceName);

        QueryResponse query = solrClient.query(solrQuery);

        return query.getResults();
    }

}
